import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Django.settings")
import django
django.setup()
from django.shortcuts import render, redirect, HttpResponse
from django.http import JsonResponse
import logging
logging.basicConfig(level=logging.INFO)
from sm_system.models import *
from salesRecord.views import record_list
from customer.views import index as customer_index
from commodity.views import commodity_info
from supplier.views import index as supplier_index
from contract.views import index as contract_index
from tools import encrypt_md5, id_generate
# Create your views here.



BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
COOKIE_NAME = 'sm_session'


def index(request):

    id = str(request.COOKIES.get(COOKIE_NAME))[4:]
    context = {'user': None, 'admin': ''}
    if not id:
        context['user'] = ''
    else:
        try:
            context['user'] = AdminInfo.objects.get(id=id).name
        except Exception as e:
            logging.info(e)

        context['admin'] = 'admin'
    return render(request, 'juniorAdmin/index_sm.html', context)


def login(request):

    return render(request, 'juniorAdmin/login_sm.html')


def authenticate(request):

    id = request.POST.get('id')
    password = request.POST.get('password')

    content = {'message': '', 'user': None, 'admin': ''}
    try:
        admin_info = AdminInfo.objects.get(id=id)
    except Exception as e:
        logging.info(e)
        content['message'] = '该用户不存在！'
        return JsonResponse(content)

    if encrypt_md5(password) == admin_info.password:
        content['user'] = admin_info.name
        res = JsonResponse(content)
        res.set_cookie(COOKIE_NAME, (admin_info.supermarket_id+admin_info.id), max_age=86400, httponly=True)
        return res
    else:
        content['message'] = '输入的信息有误！'
        return JsonResponse(content)


def logout(request):

    rep = redirect("/juniorAdmin/login/")
    rep.delete_cookie(COOKIE_NAME)  # 删除用户浏览器上之前设置的cookie值
    return rep


def identification(request):

    id = request.COOKIES.get(COOKIE_NAME)
    if not id:
        return False
    else:
        return True


# 查询供应商记录
def view_supplier(request):

    if not identification(request):
        return redirect('/juniorAdmin/login/')
    else:
        return supplier_index(request)


# 供应商编号生成
def supplier_id(request):

    flag = True
    while flag:
        temp_id = id_generate(how_many=1, length=6)[0]
        try:
            SupplierInfo.objects.get(id=temp_id)
        except Exception as e:
            logging.info(e)
            only_id = temp_id
            flag = False
    context = {'supplier_id': str(only_id)}
    return JsonResponse(context)


# 显示职员信息
def view_clerk(request):

    if not identification(request):
        redirect('/juniorAdmin/login/')
    else:
        supermarket_id = str(request.COOKIES.get(COOKIE_NAME))[0:4]
        clerks = ClerkInfo.objects.filter(supermarket_id=supermarket_id)
        context = {'clerks': clerks}
        return render(request, 'clerk.html', context)


# 显示合同信息
def view_contract(request):

    if not identification(request):
        redirect('/juniorAdmin/login/')
    else:
        return contract_index(request)


# 生成合同编号
def contract_id(request):

    flag = True
    while flag:
        temp_id = id_generate(how_many=1, length=8)[0]
        try:
            ContractInfo.objects.get(id=temp_id)
        except Exception as e:
            logging.info(e)
            only_id = temp_id
            flag = False
    context = {'contract_id': str(only_id)}
    return JsonResponse(context)


if __name__ == '__main__':

    # authenticate('00021352647', '123456')
    pass

